﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Data.Objects.DataClasses;
using System.Data.Objects;

namespace IRC.IRepairClouds.DataLayer.Cache
{
    public abstract class VolatileSelector<TEntity> where TEntity : EntityObject
    {
        public abstract Expression<Func<TEntity, bool>> EntitySelector { get; }
        public abstract Func<ICloudRepairEntities, ObjectQuery<TEntity>> CollectionSelector { get; }

        public TRes Select<TRes>(Expression<Func<TEntity, TRes>> selector)
        {
            using (ICloudRepairEntities db = new ICloudRepairEntities()) {
                return CollectionSelector(db).Where(EntitySelector).Select(selector).GetSingle();
            }
        }

        public TRet Select<TRes, TRet>(Expression<Func<TEntity, TRes>> selector, Func<TRes, TRet> postprocess)
        {
            using (ICloudRepairEntities db = new ICloudRepairEntities()) {
                var res = CollectionSelector(db).Where(EntitySelector).Select(selector).GetSingle();
                return postprocess(res);
            }
        }
    }
}
